package com.markerhub.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.markerhub.common.dto.ChooseDto;
import com.markerhub.common.dto.CourseDto;
import com.markerhub.common.dto.PassDto;
import com.markerhub.common.dto.ReturnDto;
import com.markerhub.common.lang.Const;
import com.markerhub.common.lang.Result;
import com.markerhub.entity.*;
import com.markerhub.service.*;
import com.markerhub.utils.CSVUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotEmpty;
import javax.servlet.http.HttpServletRequest;
import javax.xml.ws.Service;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.security.Principal;
import java.time.LocalDate;
import java.util.*;

import static cn.hutool.core.util.StrUtil.isNotBlank;
import static cn.hutool.core.util.StrUtil.join;

import static org.apache.tomcat.util.codec.binary.StringUtils.newStringUtf8;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wang
 * @since 2022-03-31
 */
@RestController
@RequestMapping("/sys/course")
public class SysCourseController extends BaseController {
    @Autowired
    SysCourseApplyService sysCourseApplyService;

    @Autowired
    SysLocationService sysLocationService;

    @Autowired
    SysCourseLocationService sysCourseLocationService;

    @Autowired
    SysCourseService sysCourseService;//注入service

    @Autowired
    SysCourseAppService sysCourseAppService;//注入service

    @Autowired
    SysUserCourseService sysUserCourseService;//注入service

    @Autowired
    SysCourseMajorService sysCourseMajorService;//注入service

    @Autowired
    SysSemesterCourseService sysSemesterCourseService;//注入service

    @Autowired
    SysSemesterService sysSemesterService;//注入service

    @PostMapping("/searchAll")//管理员搜索课程
    public Result searchAll(@RequestBody CourseDto courseDto){

        List<SysCourse> sysCourses=sysCourseService.list(new QueryWrapper<SysCourse>().like(isNotBlank(courseDto.getCourseName()),"course_name",courseDto.getCourseName())
                .like(isNotBlank(courseDto.getCourseId()),"course_id",courseDto.getCourseId())
                .eq(courseDto.getCollege()!=null,"school",courseDto.getCollege()));

        if(isNotBlank(courseDto.getTeacherName())){
            //对教师名字进行模糊查询
            //获取教师列表
            List<SysUser> sysUsers=sysUserService.list(new QueryWrapper<SysUser>().eq("user_role","教师")
                    .like("name",courseDto.getTeacherName())
                    .eq("statu","在读/在职"));

            //得到教师学工号的列表
            List<String> teacherIds=new ArrayList<>();
            for(SysUser i:sysUsers){
                teacherIds.add(i.getUsername());
            }
            //遍历去除不符合条件的课程
            for(int i=sysCourses.size()-1;i>=0;i--){
                if(!teacherIds.contains(sysCourses.get(i).getTeacherId())){
                    sysCourses.remove(i);
                }
            }
        }
        //筛选地点
        if(courseDto.getLocation()!=null){
            List<SysCourseLocation> sysCourseLocations=sysCourseLocationService.list(new QueryWrapper<SysCourseLocation>().eq("location_id",courseDto.getLocation()));
            List<Long> courseIds=new ArrayList<>();
            for(int i=0;i<sysCourseLocations.size();i++){
                courseIds.add(sysCourseLocations.get(i).getCourseId());
            }
            for(int i=sysCourses.size()-1;i>=0;i--){
                if(!courseIds.contains(sysCourses.get(i).getId())){
                    sysCourses.remove(i);
                }
            }
        }
        //筛选开课学期
        if(courseDto.getSemester()!=null){
            //得到该学期的所有课程的id
            List<SysSemesterCourse> sysSemesterCourses=sysSemesterCourseService.list(new QueryWrapper<SysSemesterCourse>().eq("semester_id",courseDto.getSemester()));
            List<Long> courseIds1=new ArrayList<>();
            for(int i=0;i<sysSemesterCourses.size();i++){
                courseIds1.add(sysSemesterCourses.get(i).getCourseId());
            }
            //遍历课程的数组，筛选出去其他学期的课
            for(int i=sysCourses.size()-1;i>=0;i--){
                if(!courseIds1.contains(sysCourses.get(i).getId())){
                    sysCourses.remove(i);
                }
            }
        }
        //筛选时间
        if(courseDto.getTime()!=null){
            for(int i=sysCourses.size()-1;i>=0;i--){
                //得到每一个课程的时间的id
                List<SysCourseTime> sysCourseTimes=sysCourseTimeService.list(new QueryWrapper<SysCourseTime>().eq("course_id",sysCourses.get(i).getId()));
                List<Long> timeIds=new ArrayList<>();
                for(int j=0;j<sysCourseTimes.size();j++){
                    timeIds.add(sysCourseTimes.get(j).getTimeId());
                }
                if(!timeIds.containsAll(courseDto.getTime())){
                    sysCourses.remove(i);
                }
            }
        }
        //筛选专业
//        if(courseDto.getUsername()!=null){
//            if(Objects.equals(courseDto.getUsername(), "admin")){}
//            else{
//                SysUser stud = sysUserService.getByUsername(courseDto.getUsername());
//                if(stud==null){return Result.fail("该用户不存在");}
//                Long major = stud.getMajor();
//                for(int i=sysCourses.size()-1;i>=0;i--){
//                    //得到每一个课程的专业的id
//                    if(sysCourses.get(i).getType()==0){continue;}
//                    List<SysCourseMajor> sysCourseMajors=sysCourseMajorService.list(new QueryWrapper<SysCourseMajor>().eq("course_id",sysCourses.get(i).getId()));
//                    List<Long> majorIds=new ArrayList<>();
//                    for(int j=0;j<sysCourseMajors.size();j++){
//                        majorIds.add(sysCourseMajors.get(j).getMajorId());
//                    }
//                    if(!majorIds.contains(major)){
//                        sysCourses.remove(i);
//                    }
//                }
//
//            }
//        }

        sysCourses.forEach(u ->{
            List <SysCourseTime> s=sysCourseTimeService.listSysCourseTimeByCourseId(u.getId());
            if(s!=null) {
                u.setTime(sysCourseTimeService.generateTimeString(s));
            }
            u.setMajor(sysCourseMajorService.majorMap(u));
            u.setSemester(sysSemesterCourseService.semesterMap(u));
            u.setLocation(sysCourseLocationService.info(u.getId()));
            u.setSchoolName(sysCollegeService.getCollegeNameById(u.getSchool()));
            if(u.getTeacherId()!=null) {
                SysUser teacher = sysUserService.getOne(new QueryWrapper<SysUser>().eq("username", u.getTeacherId()));
                if (teacher != null) {
                    u.setTeacher(teacher.getName());
                }
            }
        });

        return Result.succ(sysCourses);
    }

    //于管理员相比，减少了学期的筛选功能
    @PostMapping("/search")//学生搜索课程
    public Result search(@RequestBody CourseDto courseDto){
        if(courseDto.getStatu()!=null) {
            if (Integer.valueOf(courseDto.getStatu()) == 0) {
                return Result.succ(null);
            }
        }
        Calendar cal = Calendar.getInstance();
        Integer year=cal.get(Calendar.YEAR);
        Integer month=cal.get(Calendar.MONTH)+1;
        String semester;
        if(month>7) {
            semester = year +"秋";
        }
        else {
            semester = year+"春";
        }
        SysSemester season = sysSemesterService.getOne(new QueryWrapper<SysSemester>().eq("season", semester));
        if(season!=null){
            courseDto.setSemester(season.getId());
        }
        List<SysCourse> sysCourses = (List<SysCourse>) searchAll(courseDto).getData();

        //对是否已选进行判断(不判断是否已修)
        List<SysUserCourse> isStudying = sysUserCourseService.list(new QueryWrapper<SysUserCourse>().eq("stu_username", courseDto.getUsername()).eq("isPassed", 0));
        List<Long> courseIds1=new ArrayList<>();
        if(isStudying!=null) {
            for (int i = 0; i < isStudying.size(); i++) {
                courseIds1.add(isStudying.get(i).getCourseId());
            }
            //遍历课程的数组，筛选出去以选的课程
            if(sysCourses!=null) {
                for (int i = sysCourses.size() - 1; i >= 0; i--) {

                    if (courseIds1.contains(sysCourses.get(i).getId())) {
                        sysCourses.remove(i);
                    }
                }
            }
        }
        return Result.succ(sysCourses);
    }

    @PostMapping("/stu/drop")//学生退课
    public Result stuDrop(@RequestBody ChooseDto chooseDto){
        //获得该课程的信息
        SysCourse sysCourse=sysCourseService.getById(chooseDto.getId());
        //获取学生的信息
        SysUser sysUser=sysUserService.getByUsername(chooseDto.getUsername());
        //删除选课表里的该条信息
        SysUserCourse sysUserCourse=sysUserCourseService.getOne(new QueryWrapper<SysUserCourse>()
                .eq("isPassed",0)
                .eq("course_id",chooseDto.getId())
                .eq("stu_username",chooseDto.getUsername()));
        sysUserCourseService.removeById(sysUserCourse);
        //选课人数减一
        sysCourse.setCurrentNum(sysCourse.getCurrentNum()-1);
        sysCourseService.updateById(sysCourse);

        return Result.succ("");
    }

    @PostMapping("/info")//根据课程id返回单个课程信息
    public Result info(@RequestBody SysCourse sysCourse){
        sysCourse = sysCourseService.Find(sysCourse);   //Find函数内部有对statu的判断：必须为0才会返回
        if(sysCourse==null){return Result.fail("course do not exists");}
        List <SysCourseTime> s=sysCourseTimeService.listSysCourseTimeByCourseId(sysCourse.getId());
        if(s!=null) {
            sysCourse.setTime(sysCourseTimeService.generateTimeString(s));
        }
        if(sysCourse.getTeacherId()!=null) {
            SysUser teacher = sysUserService.getOne(new QueryWrapper<SysUser>().eq("username", sysCourse.getTeacherId()));
            if (teacher != null) {
                sysCourse.setTeacher(teacher.getName());
            }
        }
        sysCourse.setMajor(sysCourseMajorService.majorMap(sysCourse));
        sysCourse.setSemester(sysSemesterCourseService.semesterMap(sysCourse));
        sysCourse.setLocation(sysCourseLocationService.info(sysCourse.getId()));
        sysCourse.setSchoolName(sysCollegeService.getCollegeNameById(sysCourse.getSchool()));
        return Result.succ(sysCourse);
    }

    @GetMapping("/list")//返回课程信息列表
    public Result listCourses(String username){
        List<SysCourse> pageData =
                sysCourseService.list(new QueryWrapper<SysCourse>().like(StrUtil.isNotBlank(username), "username", username));
        pageData.forEach(u ->{
            List <SysCourseTime> s=sysCourseTimeService.listSysCourseTimeByCourseId(u.getId());
            if(s!=null) {
                u.setTime(sysCourseTimeService.generateTimeString(s));
            }
            u.setMajor(sysCourseMajorService.majorMap(u));
            u.setSemester(sysSemesterCourseService.semesterMap(u));
            u.setLocation(sysCourseLocationService.info(u.getId()));
            u.setSchoolName(sysCollegeService.getCollegeNameById(u.getSchool()));
            if(u.getTeacherId()!=null) {
                SysUser teacher = sysUserService.getOne(new QueryWrapper<SysUser>().eq("username", u.getTeacherId()));
                if (teacher != null) {
                    u.setTeacher(teacher.getName());
                }
            }
        });
        return Result.succ(pageData);
    }

    @GetMapping("stu/chosen")//查看已选课程
    public Result stuChosen(String username){
        List<SysUserCourse> suc = sysUserCourseService.list(new QueryWrapper<SysUserCourse>().eq("stu_username", username).eq("isPassed", 0));
        ArrayList<SysCourse> pageData = new ArrayList<>();
        for (SysUserCourse i:suc){
            SysCourse temp = sysCourseService.getById(i.getCourseId());
            if(temp!=null){
                List <SysCourseTime> s=sysCourseTimeService.listSysCourseTimeByCourseId(temp.getId());
                if(s!=null) {
                    temp.setTime(sysCourseTimeService.generateTimeString(s));
                }
                if(temp.getTeacherId()!=null) {
                    SysUser teacher = sysUserService.getOne(new QueryWrapper<SysUser>().eq("username", temp.getTeacherId()));
                    if (teacher != null) {
                        temp.setTeacher(teacher.getName());
                    }
                }
                temp.setMajor(sysCourseMajorService.majorMap(temp));
                temp.setSemester(sysSemesterCourseService.semesterMap(temp));
                temp.setLocation(sysCourseLocationService.info(temp.getId()));
                temp.setSchoolName(sysCollegeService.getCollegeNameById(temp.getSchool()));
                pageData.add(temp);
            }
        }

        return Result.succ(pageData);
    }

    @GetMapping("stu/taken")//查看已选课程
    public Result stuTaken(CourseDto courseDto){
        Long semesterId = courseDto.getSemester();
        List<SysUserCourse> suc;
        if(semesterId!=null){
            SysSemester semester = sysSemesterService.getById(semesterId);
            suc = sysUserCourseService.list(new QueryWrapper<SysUserCourse>().eq("stu_username", courseDto.getUsername()).eq("isPassed", 1).eq("semester",semester.getSeason()));
        }
        else {
            suc = sysUserCourseService.list(new QueryWrapper<SysUserCourse>().eq("stu_username", courseDto.getUsername()).eq("isPassed", 1));
        }

        ArrayList<SysCourse> pageData = new ArrayList<>();
        for (SysUserCourse i:suc){
            SysCourse temp = sysCourseService.getById(i.getCourseId());
            if(temp!=null){
                List <SysCourseTime> s=sysCourseTimeService.listSysCourseTimeByCourseId(temp.getId());
                if(s!=null) {
                    temp.setTime(sysCourseTimeService.generateTimeString(s));
                }
                if(temp.getTeacherId()!=null) {
                    SysUser teacher = sysUserService.getOne(new QueryWrapper<SysUser>().eq("username", temp.getTeacherId()));
                    if (teacher != null) {
                        temp.setTeacher(teacher.getName());
                    }
                }
                temp.setMajor(sysCourseMajorService.majorMap(temp));
                temp.setSemester(sysSemesterCourseService.semesterMap(temp));
                temp.setLocation(sysCourseLocationService.info(temp.getId()));
                temp.setSchoolName(sysCollegeService.getCollegeNameById(temp.getSchool()));
                pageData.add(temp);
            }
        }

        return Result.succ(pageData);

    }

    @GetMapping("/admin/applyList")//管理员得到待审核的选课申请
    public Result adminApplyList(){
        //得到app表申请列表
        List<SysCourseApp> sysCourseApps=sysCourseAppService.list(new QueryWrapper<SysCourseApp>().eq("statu",0));
        //循环该列表，为每一个信息赋值
        for(int i=0;i<sysCourseApps.size();i++){

                SysCourse sysCourse=sysCourseService.getObjectByCourseId(sysCourseApps.get(i).getCourseId());//获取该课程的信息
                SysUser sysUser=sysUserService.getById(sysCourseApps.get(i).getUserId());//获取该学生的信息
                sysCourseApps.get(i).setStuName(sysUser.getName());
                sysCourseApps.get(i).setStuId(sysUser.getUsername());
                sysCourseApps.get(i).setCourseName(sysCourse.getCourseName());
                sysCourseApps.get(i).setCollege(sysCollegeService.getCollegeNameById(sysUser.getCollege()));
                sysCourseApps.get(i).setMajor(sysMajorService.getMajorNameById(sysUser.getMajor()));
                sysCourseApps.get(i).setTeacherName(sysUserService.getByUsername(sysCourse.getTeacherId()).getName());

        }
        ReturnDto returnDto=new ReturnDto();
        returnDto.setSysCourseApps(sysCourseApps);
        returnDto.setLength(sysCourseApps.size());
        return Result.succ(returnDto);
    }

    @PostMapping("/passStuApply")//管理员通过选课申请
    public Result passStuApply(@RequestBody SysCourseApp sysCourseApp1){
        //获取当前学期
        LocalDate localDate1 = LocalDate.now();
        String year=String.valueOf(localDate1.getYear());
        Integer month=localDate1.getMonthValue();
        String currentSeason=new String();
        if(2<month && month<8){
            currentSeason=year+'春';
        }else{
            currentSeason=year+'秋';
        }

        //获得该条申请的信息
        SysCourseApp sysCourseApp=sysCourseAppService.getById(sysCourseApp1.getId());
        //获取对应课程的信息
        SysCourse sysCourse=sysCourseService.getObjectByCourseId(sysCourseApp.getCourseId());
        //获取对应学生的信息
        SysUser sysUser=sysUserService.getById(sysCourseApp.getUserId());
       //新增选课表
        SysUserCourse sysUserCourse=new SysUserCourse();
        sysUserCourse.setCourseId(sysCourse.getId());
        sysUserCourse.setStuUsername(sysUser.getUsername());
        sysUserCourse.setSemester(currentSeason);
        sysUserCourse.setIspassed(Long.valueOf(0));
        sysUserCourseService.save(sysUserCourse);
        //该课程的选课人数和容量都加一
        sysCourse.setCurrentNum(sysCourse.getCurrentNum()+1);
        sysCourse.setVolume(sysCourse.getVolume()+1);
        sysCourseService.updateById(sysCourse);
        //在reason里加上已审核
        sysCourseApp.setStatu(1);
        sysCourseAppService.updateById(sysCourseApp);
        return Result.succ("");
    }

    @PostMapping("/apply/rejectStuApply")//管理员否决选课申请
    public Result applyRejectStuApply(@RequestBody SysCourseApp sysCourseApp1){
      SysCourseApp sysCourseApp=sysCourseAppService.getById(sysCourseApp1.getId());
      //将表里的reason加上已审核
        sysCourseApp.setRejectReason(sysCourseApp1.getRejectReason());
        sysCourseApp.setStatu(2);
        sysCourseAppService.updateById(sysCourseApp);
        return Result.succ("");
    }

    @PostMapping ("/list/teacher")
    public Result listTeacher(@RequestBody SysCourse sysCourse){
        List<SysCourse> pageData =
                sysCourseService.list(new QueryWrapper<SysCourse>()
                        .eq("teacher_id", sysCourse.getTeacherId()));
        pageData.forEach(u ->{
            List <SysCourseTime> s=sysCourseTimeService.listSysCourseTimeByCourseId(u.getId());
            if(s!=null) {
                u.setTime(sysCourseTimeService.generateTimeString(s));
            }
            u.setMajor(sysCourseMajorService.majorMap(u));
            u.setSemester(sysSemesterCourseService.semesterMap(u));
            u.setLocation(sysCourseLocationService.info(u.getId()));
            u.setSchoolName(sysCollegeService.getCollegeNameById(u.getSchool()));
            if(u.getTeacherId()!=null) {
                SysUser teacher = sysUserService.getOne(new QueryWrapper<SysUser>().eq("username", u.getTeacherId()));
                if (teacher != null) {
                    u.setTeacher(teacher.getName());
                }
            }
        });
        return Result.succ(pageData);
    }

    @PostMapping("/choose")//学生选课接口
    public Result studentChoose(@RequestBody  ChooseDto chooseDto) {
        //获取当前学期
        LocalDate localDate1 = LocalDate.now();
        String year=String.valueOf(localDate1.getYear());
        Integer month=localDate1.getMonthValue();
        String currentSeason=new String();
        if(2<month && month<8){
            currentSeason=year+'春';
        }else{
            currentSeason=year+'秋';
        }
        //获取课程的信息
        SysCourse sysCourse = sysCourseService.getOne(new QueryWrapper<SysCourse>().eq("id", chooseDto.getId()));
        //获取学生的信息
        SysUser sysUser = sysUserService.getOne(new QueryWrapper<SysUser>().eq("username", chooseDto.getUsername()));
           int j=0;
            //先判断课程是否已经修过
            QueryWrapper<SysUserCourse> queryWrapper = new QueryWrapper<>();
            queryWrapper.
                    eq("isPassed", 1)
                    .eq("stu_username", chooseDto.getUsername());
            List<SysUserCourse> sysUserCourses = sysUserCourseService.list(queryWrapper);
            j=0;
            for (SysUserCourse i:sysUserCourses) {
                if (Objects.equals(i.getCourseId(), chooseDto.getId())) {
                    j=1;
                }
                //判断已经修过的课程名字是否和这个相同
                if(Objects.equals(sysCourseService.getCourseNameById(i.getCourseId()), sysCourse.getCourseName())){
                    j=1;
                }
            }
            if(j==1){
                return Result.fail("您已修过该课程，不可再选");
            }else{
                //没有修过
                //判断同类课程的门数
                QueryWrapper<SysUserCourse> query=new QueryWrapper<>();
                query.
                        eq("isPassed",0)
                        .eq("stu_username",chooseDto.getUsername());
                //得到该学生选了哪些课
                List<SysUserCourse> sysUserCourse=sysUserCourseService.list(query);
                j=0;
                for (SysUserCourse userCourse : sysUserCourse) {

                    if (Objects.equals(sysCourseService.getById(userCourse.getCourseId()).getCourseId().substring(0,10),sysCourse.getCourseId().substring(0,10))) {
                        j = 1;
                    }
                }
                if(j==0){//可以选
                    //判断课程时间是否冲突
                    j=0;
                    for (SysUserCourse userCourse : sysUserCourse) {
                        if (sysCourseService.crash(chooseDto.getId(), userCourse)) {
                            j = 1;
                        }
                    }
                    if(j==1){
                        return Result.fail("课程时间冲突");
                    }else{
                        //课程类型
                        if(sysCourse.getType()==0){
                            //选课成功
                            SysUserCourse sysUserCourse1=new SysUserCourse();
                            sysUserCourse1.setStuUsername(chooseDto.getUsername());
                            sysUserCourse1.setCourseId(chooseDto.getId());
                            sysUserCourse1.setIspassed(Long.valueOf(0));
                            sysUserCourse1.setSemester(currentSeason);
                            sysUserCourseService.save(sysUserCourse1);
                            //选课人数加一
                            sysCourse.setCurrentNum(sysCourse.getCurrentNum()+1);
                            sysCourseService.updateById(sysCourse);
                            return Result.succ("");
                        }else{
                            //判断该专业是否可选
                            List<SysCourseMajor> sys=sysCourseMajorService.list(new QueryWrapper<SysCourseMajor>().eq("course_id",chooseDto.getId()));
                            List<Long> majorIds=new ArrayList<>();
                            for (SysCourseMajor sy : sys) {
                                majorIds.add(sy.getMajorId());
                            }
                            if(majorIds.contains(sysUser.getMajor())){//可选
                                SysUserCourse sysUserCourse2=new SysUserCourse();
                                sysUserCourse2.setStuUsername(chooseDto.getUsername());
                                sysUserCourse2.setCourseId(chooseDto.getId());
                                sysUserCourse2.setIspassed(Long.valueOf(0));
                                sysUserCourse2.setSemester(currentSeason);
                                sysUserCourseService.save(sysUserCourse2);
                                //选课人数加一
                                sysCourse.setCurrentNum(sysCourse.getCurrentNum()+1);
                                sysCourseService.updateById(sysCourse);
                                return Result.succ("");
                            }else{
                                return Result.fail("您的专业不可选此课");
                            }
                        }
                    }

                }else{
                    return Result.fail("您已选过该类课程，不可再选");
                }
            }


    }

    //正式保存课程信息：管理员保存课程信息/管理员审核通过新增、修改课程申请都通过此接口
    @PostMapping("/save")
    public Result save(@Validated @RequestBody SysCourse sysCourse){

        sysCourse=sysCourseService.process(sysCourse);

        if(sysCourse.getStatu()==null) {
            sysCourse.setStatu(0);
        }

        if(sysCourse.getStatu()==0) {
            String CourseId = sysCourseService.checkDuplicateId(sysCourse);
            if(CourseId!=null) {
                sysCourse.setCourseId(CourseId);
            }
        }
        if(!sysCourseService.checkTeacherBusy(sysCourse)&&sysCourse.getStatu()==0){
            return Result.fail("教师上课时间重复");
        }
        if (!sysCourseService.checkLocationBusy(sysCourse)&&sysCourse.getStatu()==0) {
            return Result.fail("教室此时间已有课程！");
        }
        Map<Long,String> time=sysCourse.getTime();
        SysLocation location = sysCourse.getLocation();
        Map<Long,String> semester = sysCourse.getSemester();
        Map<Long, String> major = sysCourse.getMajor();
        sysCourse.setId(null);
        //sysCourse.setSchool(sysCollegeService.getIdByCollege(sysCourse.getSchoolName()));
        sysCourseService.save(sysCourse);       //保存基础信息
        sysCourse=sysCourseService.getOne(new QueryWrapper<SysCourse>().orderByDesc("id").last("limit 1"));
        sysCourseTimeService.saveTime(sysCourse.getId(),time); //保存时间信息
        sysCourseLocationService.saveLocation(sysCourse.getId(),location);      //保存地点信息
        sysSemesterCourseService.saveSemester(sysCourse.getId(),semester);      //保存学期信息
        if(sysCourse.getType()==1) { sysCourseMajorService.saveMajor(sysCourse.getId(),major); }         //保存专业信息
        return Result.succ(info(sysCourse));
    }

    //管理员直接修改课程信息
    //添加事务管理，如果修改失败回滚
    @Transactional
    @PostMapping("/update/admin")//管理员直接修改课程信息
    public Result updateAdmin(@RequestBody SysCourse sysCourse){
        //修改课程基础信息
        if(sysCourse.getStatu()==null) {
            sysCourse.setStatu(0);
        }
        sysCourseService.updateById(sysCourse);
        //修改课程时间、地点、学期、专业信息
        //进行entity的处理   将id转化为map
        sysCourse=sysCourseService.process(sysCourse);

        //修改地点
        //1.删除原有的地点
        Map<String,Object>location=new TreeMap<>();
        location.put("course_id",sysCourse.getId());
        sysCourseLocationService.removeByMap(location);
        //2.查教室时间是否有重复
        if (!sysCourseService.checkLocationBusy(sysCourse)&&sysCourse.getStatu()==0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.fail("教室此时间已有课程！");
        }
        //3.增加修改后的上课教室
        sysCourseLocationService.saveLocation(sysCourse.getId(),sysCourse.getLocation());

        //修改时间
        //1.删除原有的时间
        Map<String,Object> map = new HashMap<>();
        map.put("course_id",sysCourse.getId());
        sysCourseTimeService.removeByMap(map);
        //2.查教师上课时间是否重复
        if(!sysCourseService.checkTeacherBusy(sysCourse)&&sysCourse.getStatu()==0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.fail("教师上课时间重复");
        }
        //3.新增修改后的上课时间
        sysCourseTimeService.saveTime(sysCourse.getId(),sysCourse.getTime());

        //修改学期
        //1.删除原有的学期
        Map<String,Object>semester=new TreeMap<>();
        semester.put("course_id",sysCourse.getId());
        sysSemesterCourseService.removeByMap(semester);
        //2.增加修改后的学期
        sysSemesterCourseService.saveSemester(sysCourse.getId(),sysCourse.getSemester());

        //修改专业
        //1.删除原有的专业
        Map<String,Object>major=new TreeMap<>();
        major.put("course_id",sysCourse.getId());
        sysCourseMajorService.removeByMap(major);
        //2.增加修改后的学期
        sysCourseMajorService.saveMajor(sysCourse.getId(),sysCourse.getMajor());

        return Result.succ("修改课程成功");
    }

    @PostMapping("/delete/admin")//管理员直接删除课程的接口
    public Result deleteAdmin(@RequestBody SysCourse sysCourse){
        SysCourse s1 = sysCourseService.getOne(new QueryWrapper<SysCourse>().eq("id", sysCourse.getId()));
        if(s1==null)return Result.fail("未找到该课程");

        //判断课程的学生是否为空
        List<SysUserCourse> s=sysUserCourseService.list(new QueryWrapper<SysUserCourse>()
                .eq("course_id",sysCourse.getId()));
        if(s.isEmpty()){
            //删除课程时间表里的信息
            Map<String,Object> map = new HashMap<>();
            map.put("course_id",sysCourse.getId());
            sysCourseTimeService.removeByMap(map);
            //删除课程地点表里的信息
            sysCourseLocationService.removeByMap(map);
            //删除course表的该条信息
            sysCourseService.removeById(sysCourse.getId());
            //删除course major里的信息
            sysCourseMajorService.removeByMap(map);
            //删除课程学期表里的信息
            sysSemesterCourseService.removeByMap(map);
            return Result.succ("");
        }else{
            return Result.fail("该课程不能删除，还有学生正在修读此课程");
        }

    }

    @PostMapping("/memberList")//管理员查看选课名单
    public Result memberList(@RequestBody SysCourse sysCourse){
        //获取当前的学期
        LocalDate localDate1 = LocalDate.now();
        String year=String.valueOf(localDate1.getYear());
        Integer month=localDate1.getMonthValue();
        String currentSeason=new String();
        if(2<month && month<8){
            currentSeason=year+'春';
        }else{
            currentSeason=year+'秋';
        }
        sysCourse=sysCourseService.getOne(new QueryWrapper<SysCourse>().eq("course_id",sysCourse.getCourseId()));

        List<SysUserCourse> sysUserCourses=sysUserCourseService.list(new QueryWrapper<SysUserCourse>().eq("isPassed",0)
                .eq("course_id",sysCourse.getId())
                .eq("semester",currentSeason));
        List<SysUser> sysUsers=new ArrayList<>();

        for(int i=0;i<sysUserCourses.size();i++){
            sysUsers.add(sysUserService.getByUsername(sysUserCourses.get(i).getStuUsername()));
        }
        sysUsers.forEach(u->
        {
            u.setCollegeName(sysCollegeService.getCollegeNameById(u.getCollege()));
            u.setMajorName(sysMajorService.getMajorNameById(u.getMajor()));
        });
        ReturnDto returnDto=new ReturnDto();
        returnDto.setSysUsers(sysUsers);
        returnDto.setLength(sysUsers.size());
        return Result.succ(returnDto);
    }

    @PostMapping("/stu/apply")//学生提交选课申请
    public Result stuApply(@RequestBody SysCourseApp sysCourseApp){
        List<SysCourse> sysCourse=sysCourseService.list(new QueryWrapper<SysCourse>().eq("course_id",sysCourseApp.getCourseId()));
//判断是否已申请过
        Long id=sysUserService.getByUsername(sysCourseApp.getUsername()).getId();
        List<SysCourseApp> sysCourseapp=sysCourseAppService.list(new QueryWrapper<SysCourseApp>().eq("course_id",sysCourseApp.getCourseId()).eq("user_id",id));

        if(sysCourse.isEmpty()){
            return Result.fail("您输入的课程编码不正确");
        }else if(!sysCourseapp.isEmpty()){
            return Result.fail("您已申请过该课程");
        }else{
            sysCourseApp.setUserId(sysUserService.getByUsername(sysCourseApp.getUsername()).getId());
            sysCourseApp.setCourseId(sysCourseApp.getCourseId());
            sysCourseApp.setReason(sysCourseApp.getReason());
            sysCourseApp.setStatu(0);
            sysCourseAppService.save(sysCourseApp);

            return Result.succ("");
        }

    }

    @PostMapping("/stu/applyList")//学生查看选课申请
    public Result stuApplyList(@RequestBody SysUser sysUser){
        //获取该学生的信息
        SysUser sysUser1=sysUserService.getByUsername(sysUser.getUsername());
        //获取该学生所有的选课申请
        List<SysCourseApp> sysCourseApps=sysCourseAppService.list(new QueryWrapper<SysCourseApp>().eq("user_id",sysUser1.getId()));
        //给每一个赋值
        for(int i=0;i<sysCourseApps.size();i++){
                SysCourse sysCourse=sysCourseService.getObjectByCourseId(sysCourseApps.get(i).getCourseId());//获取该课程的信息
                sysCourseApps.get(i).setStuName(sysUser1.getName());
                sysCourseApps.get(i).setStuId(sysUser1.getUsername());
                sysCourseApps.get(i).setCourseName(sysCourse.getCourseName());
                sysCourseApps.get(i).setCollege(sysCollegeService.getCollegeNameById(sysUser1.getCollege()));
                sysCourseApps.get(i).setMajor(sysMajorService.getMajorNameById(sysUser1.getMajor()));
                sysCourseApps.get(i).setTeacherName(sysUserService.getByUsername(sysCourse.getTeacherId()).getName());

        }
        ReturnDto returnDto=new ReturnDto();
        returnDto.setSysCourseApps(sysCourseApps);
        returnDto.setLength(sysCourseApps.size());
        return Result.succ(returnDto);
    }


//    @PostMapping("/save/batch")
//    public Result saveBatch(HttpServletRequest request){
//        String filePath = request.getParameter("filePath");
//        List<String> dataList = CSVUtils.importCsv(new File(filePath));
//        if (dataList != null && !dataList.isEmpty()) {
//            for (int i = 1; i < dataList.size(); i++) {
//                String data = dataList.get(i);
//                String[] source = data.split(",");
//                if (source[0] != "") {
//                    SysCourse sysCourse = new SysCourse();
//                    sysCourse.setId(Long.valueOf(source[0]));
//                    sysCourse.setCourseName(source[1]);
//                    sysCourse.setCourseId(Long.valueOf(source[2]));
//                    sysCourse.setSchool(source[3]);
//                    sysCourse.setCredit(Integer.valueOf(source[4]));
//                    sysCourse.setHour(Integer.valueOf(source[5]));
//                    sysCourse.setMajor(source[6]);
//                    sysCourse.setTeacher(source[7]);
//                    sysCourse.setTeacherId(source[8]);
//                    sysCourse.setIntro(source[9]);
//                    sysCourse.setVolume(Long.valueOf(source[10]));
//                    for (int j =11 ; j < source.length;j++){
//                        SysCourseTime sysCourseTime = new SysCourseTime();
//                        sysCourseTime.setCourseId(sysCourse.getId());
//                        sysCourseTime.setTimeId(Long.valueOf(source[j]));
//                        sysCourseTimeService.save(sysCourseTime);
//                    }
//                    sysCourseService.save(sysCourse);
//                }
//            }
//            return Result.succ("导入成功！");
//
//        }
//        return Result.fail("导入失败...");
//    }


//
//    @PostMapping("/update/admin")//管理员直接修改课程信息
//    public Result updateAdmin(@RequestBody SysCourse sysCourse){
//        Result d = deleteAdmin(sysCourse);
//        if(d.getCode()==200) {
//            Result s = save(sysCourse);
//            if(s.getCode()==200){
//                SysCourse sys = sysCourseService.getOne(new QueryWrapper<SysCourse>().orderByDesc("id").last("limit 1"));
//                return Result.succ(info(sys));
//            }
//            else return s;
//        }
//        else{return d;}
//
//    }
//
//    @GetMapping("/choose")//查看可选课程
//    public Result choose(Principal principal){
//
//        SysUserRole sysUserRole=sysUserRoleService.getObject();
//        if(sysUserRole.getUserId()==0){
//            return Result.fail("未到选课时间");
//        }else{
//            String major=sysUserService.getMajorByName(principal.getName());
//            List<SysCourse> pageData = sysCourseService.list(new QueryWrapper<SysCourse>()
//                    .like(StrUtil.isNotBlank(major), "major", major));
//            pageData.forEach(
//                    u ->{
//                        u.setTime(sysCourseTimeService.listTimeByCollegeId(u.getId()));
//                        u.setLocation(sysLocationService.getLocayionByCourseId(sysCourseLocationService.getLocationByCourse(u.getId())));
//                    }
//            );
//            return Result.succ(pageData);
//        }
//
//    }
//
//    @PostMapping("apply/delete")//教师申请删除课程
//    public Result applyDelete(@RequestBody SysCourse sysCourse){//将要删除的课程的id存在target中
//
//        SysCourse sys=new SysCourse();
//        sys.setTarget(sysCourse.getId());
//        sys.setStatu(2);
//        sysCourseService.save(sys);
//        return Result.succ("");
//    }
//
//    @GetMapping("/delete/list")//管理员得到待审核的删除申请
//    public Result deleteList() {
//        List<SysCourse> pageData = sysCourseService.list(new QueryWrapper<SysCourse>()
//                .eq("statu", 2));
//        pageData.forEach(u->{
//            List<SysCourseTime> s=sysCourseTimeService.list(new QueryWrapper<SysCourseTime>()
//                    .eq("course_id", u.getId()));
//            u.setTimeId(sysCourseTimeService.generateTimeString(s));
//            u.setLocation(sysLocationService.getLocayionByCourseId(sysCourseLocationService.getLocationByCourse(u.getId())));
//        });
//        return Result.succ("");
//    }
//
//    @PostMapping("/delete")//审核删除课程信息
//    public Result delete(@RequestBody SysCourse sysCourse){
//
//        if(sysCourse.getPass()==1){
//            //删除课程表里的该条信息
//            sysCourseService.removeById(sysCourse.getTarget());
//
//            //删除课程时间表里的信息
//            Map<String,Object> map = new HashMap<>();
//            map.put("course_id",sysCourse.getTarget());
//            sysCourseTimeService.removeByMap(map);
//            //删除课程地点表里的信息
//            sysCourseLocationService.removeByMap(map);
//            //删除course表的该条信息
//            sysCourseService.removeById(sysCourse.getTarget());
//            return Result.succ("");
//        }else{
//            //删除apply表里的该条信息
//            sysCourseService.removeById(sysCourse.getId());
//            return Result.succ("");
//        }
//    }
////
//    @PostMapping("/delete/admin")//管理员直接删除课程的接口
//    public Result deleteAdmin(@RequestBody SysCourse sysCourse){
//        SysCourse s1 = sysCourseService.getOne(new QueryWrapper<SysCourse>().eq("id", sysCourse.getId()));
//        if(s1==null)return Result.fail("未找到该课程");
//
//        //判断课程的学生是否为空
//        List<SysUserCourse> s=sysUserCourseService.list(new QueryWrapper<SysUserCourse>()
//                .eq("course_id",sysCourse.getId()));
//        if(s.isEmpty()){
//            //删除课程时间表里的信息
//            Map<String,Object> map = new HashMap<>();
//            map.put("course_id",sysCourse.getId());
//            sysCourseTimeService.removeByMap(map);
//            //删除课程地点表里的信息
//            sysCourseLocationService.removeByMap(map);
//            //删除course表的该条信息
//            sysCourseService.removeById(sysCourse.getId());
//            //删除course major里的信息
//            sysCourseMajorService.removeByMap(map);
//            //删除课程学期表里的信息
//            sysSemesterCourseService.removeByMap(map);
//            return Result.succ("");
//        }else{
//            return Result.fail("该课程不能删除，还有学生正在修读此课程");
//        }
//
//    }
////
//    @PostMapping("/bat")
//    public Result bat(HttpServletRequest request){
//        SysCourse sysCourse = new SysCourse();
//        sysCourse.setCourseName(request.getParameter("courseName"));
//        sysCourse.setCourseId(Long.valueOf(request.getParameter("courseId")));
//        sysCourse.setSchool(request.getParameter("school"));
//        sysCourse.setCredit(Integer.valueOf(request.getParameter("credit")));
//        sysCourse.setHour(Integer.valueOf(request.getParameter("hour")));
//        sysCourse.setMajor(request.getParameter("major"));
//        sysCourse.setTeacher(request.getParameter("teacher"));
//        sysCourse.setTeacherId(request.getParameter("teacherId"));
//        sysCourse.setIntro(request.getParameter("intro"));
//        sysCourse.setVolume(Long.valueOf(request.getParameter("volume")));
//        sysCourseService.save(sysCourse);
//        sysCourse= sysCourseService.getOne(new QueryWrapper<SysCourse>().orderByDesc("id").last("limit 1"));
//        SysCourseLocation sysCourseLocation = new SysCourseLocation();
//        sysCourseLocation.setCourseId(sysCourse.getId());
//        Long id = sysLocationService.getByLocation(request.getParameter("location"));
//        sysCourseLocation.setLocationId(id);
//        sysCourseLocationService.save(sysCourseLocation);
//
//        List<String> Temp = Arrays.asList(request.getParameter("timeId").split("-"));
//        for (int i=0;i<Temp.size();i++) {
//            SysCourseTime sysCourseTime = new SysCourseTime();
//            sysCourseTime.setCourseId(sysCourse.getId());
//            sysCourseTime.setTimeId(Long.valueOf(Temp.get(i)));
//            sysCourseTimeService.save(sysCourseTime);
//        }
//
//        return Result.succ("导入成功");
//    }
//
//
//
//    @PostMapping("/save/pass")
//    public Result savePass(@Validated @RequestBody SysCourseApply sysCourseApply){
//        SysCourse sysCourse = new SysCourse();
//        sysCourse.setCourseId(sysCourseApply.getCourseId());
//        sysCourse.setCourseName(sysCourseApply.getCourseName());
//        sysCourse.setCredit(sysCourseApply.getCredit());
//        sysCourse.setHour(sysCourseApply.getHour());
//        sysCourse.setIntro(sysCourseApply.getIntro());
//        sysCourse.setMajor(sysCourseApply.getMajor());
//        sysCourse.setSchool(sysCourseApply.getSchool());
//        sysCourse.setTeacher(sysCourseApply.getTeacher());
//        sysCourse.setTeacherId(sysCourseApply.getTeacherId());
//        sysCourse.setVolume(sysCourseApply.getVolume());
//
//        if(sysCourseService.save(sysCourse)) {
//            sysCourse= sysCourseService.getOne(new QueryWrapper<SysCourse>().orderByDesc("id").last("limit 1"));
//            SysCourseLocation sysCourseLocation = new SysCourseLocation();
//            sysCourseLocation.setCourseId(sysCourse.getId());
//            Long id = sysLocationService.getByLocation(sysCourseApply.getLocation());
//            sysCourseLocation.setLocationId(id);
//            sysCourseLocationService.save(sysCourseLocation);
//
//            List<String> Temp = Arrays.asList(sysCourseApply.getTime().split(","));
//            for (int i=0;i<Temp.size();i++){
//                SysCourseTime sysCourseTime = new SysCourseTime();
//                sysCourseTime.setCourseId(sysCourse.getId());
//                sysCourseTime.setTimeId(Long.valueOf(Temp.get(i)));
//                sysCourseTimeService.save(sysCourseTime);
//            }
//            sysCourseApplyService.removeById(Long.valueOf(sysCourseApply.getId()));
//            return Result.succ("导入成功");
//        }
//        else
//            return Result.fail("导入失败");
//    }
//
//
//    @PostMapping("apply/update")//教师修改课程信息申请接口
//    public Result applyUpdate(@RequestBody SysCourse sysCourse){
//        //将修改后的课程信息保存到课程表里，状态设置为3，设置target为原来课程的id
//        SysCourse sys = new SysCourse();
//        sys.setCourseId(sysCourse.getCourseId());
//        sys.setCourseName(sysCourse.getCourseName());
//        sys.setCredit(sysCourse.getCredit());
//        sys.setHour(sysCourse.getHour());
//        sys.setIntro(sysCourse.getIntro());
//        sys.setSchool(sysCourse.getSchool());
//        sys.setTeacherId(sysCourse.getTeacherId());
//        sys.setVolume(sysCourse.getVolume());
//        sys.setCurrentNum(sysCourse.getCurrentNum());
//        sys.setTarget(sysCourse.getId());
//        sys.setStatu(3);
//        sysCourseService.save(sys);
//        sys=sysCourseService.getObjectByCourseId(sysCourse.getCourseId());
//        //新增时间
//        Integer size=sysCourse.getTime().size();
//        SysCourseTime sysCourseTime=new SysCourseTime();
//        for(int i = 0; i<size; i++){
//            sysCourseTime.setCourseId(sys.getId());
//            sysCourseTime.setTimeId(sysCourse.getTime().get(i));
//            sysCourseTimeService.save(sysCourseTime);
//        }
//        //新增地点
//        SysCourseLocation sysCourseLocation=new SysCourseLocation();
//        sysCourseLocation.setCourseId(sys.getId());
//        sysCourseLocation.setLocationId(sysCourse.getLocationId());
//        return Result.succ("");
//    }
//
//    @PostMapping("update")//管理员审核修改申请
//    public Result update(@RequestBody SysCourse sysCourse){//要返回id
//        //审核通过
//        //把返回的这个课程的状态改为0
//        if(sysCourse.getPass()==1){
//            sysCourse.setStatu(0);
//            sysCourseService.updateById(sysCourse);
//            //把target的课程删掉
//            sysCourseService.removeById(sysCourse.getTarget());
//            Map<String,Object> map = new HashMap<>();
//            map.put("course_id",sysCourse.getTarget());
//            sysCourseTimeService.removeByMap(map);
//            sysCourseLocationService.removeByMap(map);
//        }else{
//            //审核不通过
//            //把返回的这个课程删掉
//            Map<String,Object> map = new HashMap<>();
//            map.put("course_id",sysCourse.getId());
//            sysCourseTimeService.removeByMap(map);
//            sysCourseLocationService.removeByMap(map);
//            sysCourseService.remove(new QueryWrapper<SysCourse>().eq("id",sysCourse.getId()));
//        }
//        return Result.succ("");
//    }
//
//    @GetMapping("/update/list")//管理员得到待审核的修改申请
//    public Result updateList(){
//        List<SysCourse> pageData = sysCourseService.list(new QueryWrapper<SysCourse>()
//                .eq("statu", 3));
//        pageData.forEach(u->{
//            List<SysCourseTime> s=sysCourseTimeService.list(new QueryWrapper<SysCourseTime>()
//                    .eq("course_id", u.getId()));
//            u.setTimeId(sysCourseTimeService.generateTimeString(s));
//            u.setLocation(sysLocationService.getLocayionByCourseId(sysCourseLocationService.getLocationByCourse(u.getId())));
//        });
//        return Result.succ("");
//    }
}
